package common.zsxmlv.utils;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * @Author: ZSXM
 * @Description: 文件工具类
 * @Company: DingZheng
 * @Date: Create by 2018/6/10 12:57
 * @Version: 1.0
 * @Modify by:
 */
public class FileUtils {


    public static int strByteToImage(byte[] bytes, String imgPath, String imgName) throws IOException {
        int stateInt = 1;
//        if (imgStr != null && !"".equals(imgStr)) {

            System.out.println(bytes);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            File file = new File(imgPath, imgName);
            FileOutputStream outputStream = new FileOutputStream(file);

            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, nRead);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
//        }
        return 0;
    }

    /**
     * 二进制转字符串
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) // 二进制转字符串
    {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }

        }
        return sb.toString();
    }

    /**
     * 字符串转二进制
     * @param str 要转换的字符串
     * @return 转换后的二进制数组
     */
    public static byte[] hex2byte(String str) {
        if (str == null) {
            return null;
        }
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1) {
            return null;
        }
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer
                        .decode("0X" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }


}
